import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pagewise/flutter_pagewise.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:loxen/mode/study/study_info_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/viewmode/search_result_viewmodel.dart';

class SearchKnowledgeListWidget extends StatelessWidget {
  final PagewiseLoadController pageLoadController;

  SearchKnowledgeListWidget({Key key, this.pageLoadController}) : super(key: key) {
    pageLoadController.init();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 36.w, top: 31.h, right: 36.w),
      child: RefreshIndicator(
          onRefresh: () async {
            Provider.of<SearchResultViewModel>(context, listen: false).refresh();
            this.pageLoadController.reset();
          },
          child: PagewiseListView<StudyInfo>(
            addAutomaticKeepAlives: false,
            loadingBuilder: (_) => MySubassembly.getLoadingItem(),
            noItemsFoundBuilder: (_) => MySubassembly.getNullItem(msg: '没有更多内容'),
            pageLoadController: this.pageLoadController,
            itemBuilder: (_, entity, index) {
              if (entity.type != null) {
                if (entity.type == '1') {
                  return _ItemWidget1(
                      entity: entity,
                      studyCategory: context.read<SearchResultViewModel>().studyCategory);
                }
                if (entity.type == '2') {
                  return _ItemWidget2(
                      entity: entity,
                      studyCategory: context.read<SearchResultViewModel>().studyCategory);
                }
              }
              return Text('');
            },
          )),
    );
  }
}

class _ItemWidget1 extends StatelessWidget {
  final StudyInfo entity;
  final int studyCategory;

  const _ItemWidget1({Key key, this.entity, this.studyCategory}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print(studyCategory);
        print(entity);
//        int category = Provider.of<StudyViewModel>(context, listen: false).currentCategory;
        Navigator.of(context).pushNamed(Routes.study_detail,
            arguments: {"detail": entity, "currentCategory": studyCategory}).then((value) {
          context.read<SearchResultViewModel>().changeEntity();
        });
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        margin: EdgeInsets.only(bottom: 30.h),
        width: double.infinity,
        height: 230.h,
        padding: EdgeInsets.all(20.w),
        child: Row(
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 28.w),
              child: Stack(
                alignment: Alignment.center,
                children: <Widget>[
                  Container(
                      width: 189.w,
                      height: 189.h,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(5.w),
                        child: Image.network(
                          entity.cover,
                          fit: BoxFit.cover,
                        ),
                      )),
                  Image.asset('images/study_video.png', width: 60.w, height: 60.h),
                ],
              ),
            ),
            Expanded(
              flex: 1,
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: Text(
                            entity.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              color: Color(0xFF000000),
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          )),
                      Container(
                        margin: EdgeInsets.only(left: 20.w),
                        padding: EdgeInsets.fromLTRB(13.w, 0, 13.w, 0),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(5.w)),
                            border: Border.all(color: Color(0xFF82868E), width: 1.w)),
                        child: Text(
                          '视频',
                          style: TextStyle(
                            color: Color(0xFF82868E),
                            fontSize: 21.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      )
                    ],
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      margin: EdgeInsets.only(top: 20.h),
                      alignment: Alignment.topLeft,
                      child: Text(
                        entity.brief,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Color(0xFF82868E),
                          fontSize: 22.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                          flex: 1,
                          child: Row(
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(right: 13.w),
                                child: CircleAvatar(
                                  radius: 13,
                                  backgroundImage: NetworkImage(entity.user.portrait),
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Text(
                                  entity.user.nickname,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    color: Color(0xFF82868E),
                                    fontSize: 24.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              )
                            ],
                          )),
                      Row(
                        children: <Widget>[
                          Selector<SearchResultViewModel, int>(
                            builder: (_, __, ___) {
                              return Container(
                                margin: EdgeInsets.only(left: 50.w),
                                padding: EdgeInsets.only(right: 20.w),
                                child: SizedBox(
                                  width: 72.w,
                                  child: FlatButton(
                                    padding: EdgeInsets.all(1.w),
                                    onPressed: () {
                                      if (context.read<LoginViewModel>().isLogin()) {
                                        Navigator.of(context).pushNamed(Routes.login_page);
                                      } else {
                                        context.read<SearchResultViewModel>().likeStudy(entity);
                                      }
                                    },
                                    child: Stack(
                                      alignment: Alignment.centerLeft,
                                      children: <Widget>[
                                        Image.asset(
                                          entity.is_like == 0
                                              ? "images/like.png"
                                              : "images/like_active.png",
                                          width: 30.w,
                                          height: 30.w,
                                          fit: BoxFit.cover,
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(
                                            left: 37.w,
                                            top: 4.h,
                                          ),
                                          child: Text(
                                            '${entity.like_num}',
                                            style: TextStyle(
                                                fontSize: 22.sp,
                                                color: entity.is_like == 0
                                                    ? Color(0xFF999999)
                                                    : Color(0xFF0CABCB)),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                            selector: (_, __) => entity.is_like,
                          ),
                          Builder(builder: (context) {
                            bool collection = context.select<SearchResultViewModel, bool>(
                                (value) => entity.is_collect == 0);
                            return SizedBox(
                              width: 72.w,
                              child: FlatButton(
                                padding: EdgeInsets.all(1.w),
                                onPressed: () {
                                  if (context.read<LoginViewModel>().isLogin()) {
                                    Navigator.of(context).pushNamed(Routes.login_page);
                                    return;
                                  }
                                  if (collection) {
                                    Navigator.of(context).pushNamed(Routes.master_file_add,
                                        arguments: {
                                          'type': FileType.KNOWLEDGE,
                                          'id': entity.id.toString()
                                        }).then((value) {
                                      if (value) {
                                        entity.is_collect = 1;
                                        entity.collect_num += 1;
                                        context.read<SearchResultViewModel>().changeEntity();
                                      }
                                    });
                                  } else {
                                    context
                                        .read<SearchResultViewModel>()
                                        .unCollection(entity.id.toString(), onSuccess: () {
                                      entity.is_collect = 0;
                                      entity.collect_num -= 1;
                                    }, onError: (str) {});
                                  }
                                },
                                child: Stack(
                                  alignment: Alignment.centerLeft,
                                  children: <Widget>[
                                    Image.asset(
                                      collection ? "images/collect.png" : "images/collected.png",
                                      width: 30.w,
                                      height: 30.w,
                                      fit: BoxFit.cover,
                                    ),
                                    Padding(
                                      padding: EdgeInsets.only(
                                        left: 37.w,
                                        top: 4.h,
                                      ),
                                      child: Text(
                                        '${entity.collect_num}',
                                        style: TextStyle(
                                            fontSize: 22.sp,
                                            color:
                                                collection ? Color(0xFF999999) : Color(0xFF0CABCB)),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            );
                          }),
                        ],
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class _ItemWidget2 extends StatelessWidget {
  final StudyInfo entity;
  final int studyCategory;
  static const Widget empty = const SizedBox.shrink();

  const _ItemWidget2({Key key, this.entity, this.studyCategory}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(Routes.study_detail,
            arguments: {"detail": entity, "currentCategory": studyCategory}).then((value) {
          context.read<SearchResultViewModel>().changeEntity();
        });
      },
      child: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            height: 350.h,
            child: Image.network(
              entity.cover,
              fit: BoxFit.cover,
            ),
          ),
          Container(
            margin: EdgeInsets.only(bottom: 30.h),
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            width: double.infinity,
            padding: EdgeInsets.all(30.w),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      entity.title,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: Color(0xFF000000),
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    )),
                    entity.type != null
                        ? Container(
                            padding: EdgeInsets.fromLTRB(13.w, 0, 13.w, 0),
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(2.5)),
                                border: Border.all(color: Color(0xFF82868E), width: 0.5)),
                            child: Text(
                              '图文',
                              style: TextStyle(
                                color: Color(0xFF82868E),
                                fontSize: 21.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          )
                        : empty
                  ],
                ),
                Container(
                  margin: const EdgeInsets.only(top: 9.5, bottom: 14),
                  child: Text(
                    entity.brief,
                    maxLines: 1,
                    style: TextStyle(
                      color: Color(0xFF82868E),
                      fontSize: 22.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Row(
                              children: <Widget>[
                                Container(
                                  margin: EdgeInsets.only(right: 13.w),
                                  child: CircleAvatar(
                                    radius: 13,
                                    backgroundImage: NetworkImage(entity.user.portrait),
                                  ),
                                ),
                                Text(
                                  entity.user.nickname,
                                  style: TextStyle(
                                    color: Color(0xFF82868E),
                                    fontSize: 24.sp,
                                    fontWeight: FontWeight.w500,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      children: <Widget>[
                        Builder(builder: (context) {
                          bool isLike = context
                              .select<SearchResultViewModel, bool>((value) => entity.is_like == 0);
                          return Container(
                            margin: EdgeInsets.only(left: 50.w),
                            padding: EdgeInsets.only(right: 20.w),
                            child: SizedBox(
                              width: 72.w,
                              child: FlatButton(
                                padding: EdgeInsets.all(1.w),
                                onPressed: () {
                                  if (context.read<LoginViewModel>().isLogin()) {
                                    Navigator.of(context).pushNamed(Routes.login_page);
                                  } else {
                                    context.read<SearchResultViewModel>().likeStudy(entity);
                                  }
                                },
                                child: Stack(
                                  alignment: Alignment.centerLeft,
                                  children: <Widget>[
                                    Image.asset(
                                      isLike ? "images/like.png" : "images/like_active.png",
                                      width: 30.w,
                                      height: 30.w,
                                      fit: BoxFit.cover,
                                    ),
                                    Padding(
                                      padding: EdgeInsets.only(
                                        left: 37.w,
                                        top: 4.h,
                                      ),
                                      child: Text(
                                        '${entity.like_num}',
                                        style: TextStyle(
                                            fontSize: 22.sp,
                                            color: isLike ? Color(0xFF999999) : Color(0xFF0CABCB)),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          );
                        }),
                        Builder(builder: (context) {
                          bool collection = context.select<SearchResultViewModel, bool>(
                              (value) => entity.is_collect == 0);
                          return SizedBox(
                            width: 72.w,
                            child: FlatButton(
                              padding: EdgeInsets.all(1.w),
                              onPressed: () async {
                                if (context.read<LoginViewModel>().isLogin()) {
                                  Navigator.of(context).pushNamed(Routes.login_page);
                                  return;
                                }
                                if (collection) {
                                  Navigator.of(context).pushNamed(Routes.master_file_add,
                                      arguments: {
                                        'type': FileType.KNOWLEDGE,
                                        'id': entity.id.toString()
                                      }).then((value) {
                                    if (value) {
                                      entity.is_collect = 1;
                                      entity.collect_num += 1;
                                      context.read<SearchResultViewModel>().changeEntity();
                                    }
                                  });
                                } else {
                                  bool data = await showDialog(
                                      context: context,
                                      builder: (context) => AlertDialog(
                                            title: Text('提示'),
                                            content: Text(
                                              '是否取消收藏？',
                                              style: TextStyle(color: Colors.black),
                                            ),
                                            actions: <Widget>[
                                              FlatButton(
                                                child: Text(StringResources.qu_xiao),
                                                onPressed: () => Navigator.of(context).pop(),
                                              ),
                                              FlatButton(
                                                child: Text(StringResources.que_ding),
                                                onPressed: () {
                                                  Navigator.of(context).pop(true);
                                                },
                                              ),
                                            ],
                                          ));
                                  if (data != null && data) {
                                    context
                                        .read<SearchResultViewModel>()
                                        .unCollection(entity.id.toString(), onSuccess: () {
                                      entity.is_collect = 0;
                                      entity.collect_num -= 1;
                                      Toast.show(StringResources.qu_xiao_shou_cang, context);
                                    }, onError: (str) {
                                      Toast.show(StringResources.wang_luo_yi_chang, context);
                                    });
                                  }
                                }
                              },
                              child: Stack(
                                alignment: Alignment.centerLeft,
                                children: <Widget>[
                                  Image.asset(
                                    collection ? "images/collect.png" : "images/collected.png",
                                    width: 30.w,
                                    height: 30.w,
                                    fit: BoxFit.cover,
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(
                                      left: 37.w,
                                      top: 4.h,
                                    ),
                                    child: Text(
                                      '${entity.collect_num}',
                                      style: TextStyle(
                                          fontSize: 22.sp,
                                          color:
                                              collection ? Color(0xFF999999) : Color(0xFF0CABCB)),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          );
                        }),
                      ],
                    )
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
